import { FFmpeg } from "@ffmpeg/ffmpeg";
import { toBlobURL, fetchFile } from "@ffmpeg/util";
const baseURL = "https://unpkg.com/@ffmpeg/core@0.12.2/dist/esm";
const ffmpeg = new FFmpeg();

export async function createThumbnail(videoUrl: any) {
  ffmpeg.on("log", ({ message }: any) => {
    console.log(message);
  });
  ffmpeg.on("progress", (e: any) => {
    console.log(e);
  });

  await ffmpeg.load({
    coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
    wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
  });

  // 载入视频
  await ffmpeg.writeFile("input.mp4", await fetchFile(videoUrl));
  // 执行命令以提取第一帧
  await ffmpeg.exec([
    "-i",
    "input.mp4",
    "-vf",
    "select=gt(scene\\,0.001)",
    "-frames:v",
    "1",
    "output.jpg",
  ]);

  // 获取封面图数据
  const thumbnailData = await ffmpeg.readFile("output.jpg");
  console.log(thumbnailData);

  // 创建封面图URL
  const thumbnailUrl = URL.createObjectURL(
    new Blob([thumbnailData], { type: "image/jpeg" })
  );

  // 创建封面图Image元素
  const thumbnailImage = new Image();
  thumbnailImage.src = thumbnailUrl;

  return thumbnailImage;
}
